package com.zhijian.wharf.controller.web;

import com.alibaba.fastjson.JSON;
import com.zhijian.entity.ChangePwdVo;
import com.zhijian.response.annotation.Response;
import com.zhijian.wharf.annotation.LogOperation;
import com.zhijian.wharf.config.Constants;
import com.zhijian.wharf.entity.vo.request.WebLoginVo;
import com.zhijian.wharf.entity.vo.response.AuthVo;
import com.zhijian.wharf.entity.vo.response.CaptchaVo;
import com.zhijian.wharf.holder.CurrentWebUserHolder;
import com.zhijian.wharf.service.impl.WebLoginServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 登录相关
 *
 * @author HCG
 * @version 1.0
 * @date 2022/1/17
 */
@Slf4j
@Controller
@Api(tags = "登录相关")
public class LoginController {

    @Autowired
    @Qualifier("webLoginServiceImpl")
    private WebLoginServiceImpl webLoginServiceImpl;

    /**
     * 登录
     *
     * @param vo
     */
    @Response
    @PostMapping("/login")
    @ApiOperation("登录")
    @LogOperation("登录")
    public AuthVo login(@RequestBody WebLoginVo vo) {
        if (Objects.isNull(vo.getNoCaptcha())) {
            //默认使用验证码
            vo.setNoCaptcha(false);
        }
        log.info("{}| login ", JSON.toJSONString(vo));
        return webLoginServiceImpl.login(vo);
    }

    /**
     * 用户登出
     *
     * @param token
     * @return
     */
    @Response
    @GetMapping("/logout")
    @ApiOperation("退出登录")
    @LogOperation("退出登录")
    public boolean logout(@RequestHeader(value = Constants.wharf_WEB_TOKEN) String token) {
        log.info("{}| logout info", token);
        return webLoginServiceImpl.logout(token);
    }

    /**
     * 修改密码
     *
     * @param param
     * @return
     */
    @Response
    @PutMapping("/change/password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public boolean updatePassWord(@RequestBody ChangePwdVo param) {
        log.info("{}| update info, {}", param);
        webLoginServiceImpl.changePassword(CurrentWebUserHolder.getUser().getId(), param.getOldPassword(), param.getNewPassword());
        return true;
    }

    /**
     * 生成验证码
     *
     * @return
     */
    @Response
    @PostMapping("/captcha")
    @ApiOperation("生成验证码")
    public CaptchaVo generateCaptcha() {
        return webLoginServiceImpl.generateCaptcha();
    }
}
